package com.res.simulator.transformer;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.res.common.transformer.BaseTransformer;
import com.res.simulator.handler.CommonFileHandler;
import com.res.simulator.model.GenericAPIExecutionModel;
import com.res.simulator.view.ResultView;
import com.sip.dbadapter.dao.domain.ApiDefinition;
import com.sip.dbadapter.dao.domain.ScenarioRecord;
import com.sip.dbadapter.domain.registry.DomainRegistry;

public class APIInvocationTransformer implements BaseTransformer<GenericAPIExecutionModel, ResultView, Map<String, Object>> {

    public Map<String, Object> transformModelToDomian(final GenericAPIExecutionModel model) throws Exception {

        final Map<String, Object> domainMap = new HashMap<String, Object>();
        final ApiDefinition apiDefinitionDomainObj = new ApiDefinition();
        final ScenarioRecord scenarioRecordDomainObj = new ScenarioRecord();

        apiDefinitionDomainObj.setApiId(Long.valueOf(model.getApiId()));
        apiDefinitionDomainObj.setPackageHierachy(model.getPackageName());
        scenarioRecordDomainObj.setConsumeValue(model.getConsumerString());

        domainMap.put(DomainRegistry.API_DEFINITION, apiDefinitionDomainObj);
        domainMap.put(DomainRegistry.SCENARIO_RECORD, scenarioRecordDomainObj);

        return domainMap;
    }

    public ResultView transformDomianToView(final Map<String, Object> domainMap) throws Exception {

        // TODO Auto-generated method stub
        final ResultView restServiceView = new ResultView();
        final ScenarioRecord scenarioRecordDomainObj = (ScenarioRecord) domainMap.get(DomainRegistry.SCENARIO_RECORD);
        final ApiDefinition apiDefinitionObje = (ApiDefinition) domainMap.get(DomainRegistry.API_DEFINITION);
        final CommonFileHandler fileHandler = new CommonFileHandler();

        restServiceView.setResult(scenarioRecordDomainObj.getResult());
        restServiceView.setApiName(apiDefinitionObje.getName());
        restServiceView.setInputParams(scenarioRecordDomainObj.getConsumeValue());
        restServiceView.setRecordId(scenarioRecordDomainObj.getRecordId());
        restServiceView.setApiName(scenarioRecordDomainObj.getApiDefinitionScenarioRecord().getName());

        final String fileName = generateFileName(scenarioRecordDomainObj.getRecordId());
        final String fileUrl = fileHandler.save(scenarioRecordDomainObj.getResult(), fileName);

        restServiceView.setLocation(fileUrl);
        return restServiceView;
    }

    private String generateFileName(Long recordId) throws Exception {

        final Date now = new Date();

        final String channel = "API_Execute_" + recordId;

        final String fileName = channel + "-" + now.getTime() + ".xml";

        return fileName;
    }

}
